package com.icodingedu.springcloud.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

@Configuration
public class RedisLimiterConfiguration {

    //ID : 限流的业务标识
    //根据用户请求IP地址进行限流
    @Bean
    @Primary //一个系统不止一个KeyReslover
    public KeyResolver remoteAddressKeyResolver(){
        return exchange -> Mono.just(
            exchange.getRequest()
                .getRemoteAddress()
                .getAddress()
                .getHostAddress()
        );
    }

    @Bean("redisLimiterUser")
    @Primary
    public RedisRateLimiter redisRateLimiterUser(){
        //defaultReplenishRate:生成令牌的速率,每秒10个
        //defaultBurstCapacity:桶大小
        return new RedisRateLimiter(1,2);
    }

    @Bean("redisLimiterProduct")
    public RedisRateLimiter redisRateLimiterProduct(){
        //defaultReplenishRate:生成令牌的速率,每秒10个
        //defaultBurstCapacity:桶大小
        return new RedisRateLimiter(20,100);
    }
}
